package com.groupbuying.cheetah.order.orderManagement;

import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils;
import com.groupbuying.cheetah.common.FilterContextHandler;
import com.groupbuying.cheetah.common.PageUtils;
import com.groupbuying.cheetah.common.Query;
import com.groupbuying.cheetah.utils.DateUtils;
import com.groupbuying.cheetah.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/orderManagement")
public class OrderManagementController {

    private static Logger logger = LoggerFactory.getLogger(OrderManagementController.class);

    @Autowired
    private OrderManagementDAO orderManagementDAO;

    @GetMapping("/list")
    public PageUtils orderManagement(@RequestParam Map<String, Object> params) {
        String providerId = FilterContextHandler.getName();
        params.put("providerId", providerId);
        Query query = new Query(params);
        List<OrderManagementDO> orderManagementDOList = orderManagementDAO.orderManagement(query);
        int total = orderManagementDAO.count(params);
        PageUtils pageUtils = new PageUtils(orderManagementDOList, total);
        return pageUtils;
    }

    @GetMapping("/listForFront")
    public Map orderManagementForFront(@RequestParam Map<String, Object> params) throws ParseException {
        logger.error("orderManagementForFront:" + JsonUtils.objectToJson(params));
        Map<String, Object> resultMap = new HashMap<>();
        String providerId = FilterContextHandler.getName();
        params.put("providerId", providerId);
        //先查服务商下面的所有门店（门店ID）
        List<Map<String, String>> counterList = orderManagementDAO.getStoreCheckoutCounter(params);
        logger.error("收银台查询结果" + JsonUtils.objectToJson(counterList));
        String startTime = (String) params.get("startTime");
        String endTime = (String) params.get("endTime");
        if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime) || counterList.size() <= 0) {
            resultMap.put("total", 0);
            resultMap.put("rows", new ArrayList());
            resultMap.put("totalAmount", 0);
            return resultMap;
        }
        Map<String, Map<String, String>> counterMap = new HashMap<>();
        for (Map<String, String> counter : counterList) {
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(counter.get("counterId"))){
                counterMap.put(counter.get("counterId"), counter);
            }

        }


        if ( counterMap.keySet().size() <= 0) {
            resultMap.put("total", 0);
            resultMap.put("rows", new ArrayList());
            resultMap.put("totalAmount", 0);
            return resultMap;
        }
        //订单
        params.put("counterIds", counterMap.keySet());
        Query query = new Query(params);
        List<Map<String, Object>> orderList = orderManagementDAO.queryOrderByCounterIds(query);
        logger.info("订单查询结果：{}",JsonUtils.objectToJson(orderList));
        if (orderList.size() <= 0) {
            resultMap.put("total", 0);
            resultMap.put("rows", new ArrayList());
            resultMap.put("totalAmount", 0);
            return resultMap;
        }
        List<String> customerIds = new ArrayList<>();
        Map<String, Map<String, Object>> orderMap = new HashMap<>();
        for (Map<String, Object> order : orderList) {
            orderMap.put(order.get("orderId").toString(), order);
            customerIds.add(order.get("customerId").toString());
        }
        //支付信息
        Map<String, Map<String, Object>> payMap = new HashMap<>();
        List<Map<String, Object>> payInfoList = orderManagementDAO.queryPayInfoByOrderIds(orderMap.keySet().toArray(new String[orderMap.keySet().size()]));
        logger.info("支付信息查询结果：{}",JsonUtils.objectToJson(payInfoList));
        for (Map<String, Object> payInfo : payInfoList) {
            payMap.put(payInfo.get("orderId").toString(), payInfo);
        }
        //分账信息
        Map<String, String> settleMap = new HashMap<>();
        List<Map<String, Object>> settleMoneyList = orderManagementDAO.getSettleUshopSplitMaininfo(orderMap.keySet().toArray(new String[orderMap.keySet().size()]));
        logger.info("分账信息查询结果：{}",JsonUtils.objectToJson(settleMoneyList));
        for (Map<String, Object> settleMoney : settleMoneyList) {
            settleMap.put(settleMoney.get("orderId").toString(), settleMoney.get("amount").toString());
        }
        //用户信息
        Map<String, String> customerMap = new HashMap<>();
        List<Map<String, String>> customerList = orderManagementDAO.getCustomerUshop(customerIds.toArray(new String[customerIds.size()]));
        logger.info("用户信息查询结果：{}",JsonUtils.objectToJson(customerList));
        for (Map<String, String> customer : customerList) {
            customerMap.put(customer.get("customerId"), customer.get("mobile"));
        }
        List<OrderManagementDO> orderManagementDOList = new ArrayList<>(orderList.size());
        for (Map<String, Object> order : orderList) {
            String orderId = order.get("orderId").toString();
            String counterId = order.get("counterId").toString();
            String customerId = order.get("customerId").toString();
            String amount = settleMap.get(orderId);
            String orderPrice = order.get("orderPrice").toString();
            OrderManagementDO orderManagementDO = new OrderManagementDO();
            orderManagementDO.setOrderId(orderId);
            orderManagementDO.setPayType(payMap.get(orderId).get("payType").toString());
            orderManagementDO.setOrderType(order.get("orderType").toString());
            orderManagementDO.setCounterName(counterMap.get(counterId).get("counterName"));
            orderManagementDO.setMobile(customerMap.get(customerId));
            orderManagementDO.setStoreName(counterMap.get(counterId).get("storeName"));
            orderManagementDO.setOrderPrice(orderPrice);
            orderManagementDO.setStoreId(counterMap.get(counterId).get("storeUuid"));
            String create = order.get("gmtCreate").toString();
            Date time = DateUtils.parse(create,DateUtils.YMDHMS);
            orderManagementDO.setGmtCreate(time);
            orderManagementDO.setAmount(settleMap.get(orderId));
            if ("积分支付".equals(orderManagementDO.getPayType())) {
                orderManagementDO.setPayMoney(payMap.get(orderId).get("payCur").toString());
            } else if ("余额支付".equals(orderManagementDO.getPayType())) {
                orderManagementDO.setPayMoney(payMap.get(orderId).get("payBalance").toString());
            } else {
                orderManagementDO.setPayMoney(payMap.get(orderId).get("payMoney").toString());
            }
            orderManagementDOList.add(orderManagementDO);

        }
        List<String> orderIds = orderManagementDAO.getOrderIds(params);
        BigDecimal totalAmount =orderManagementDAO.getTotalPrice(orderIds.toArray(new String[orderIds.size()] )).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal realityAmount =orderManagementDAO.getTotalAmount(orderIds.toArray(new String[orderIds.size()] )).setScale(2, BigDecimal.ROUND_HALF_UP);
        resultMap.put("total", orderIds.size());
        resultMap.put("rows", orderManagementDOList);
        resultMap.put("totalAmount", totalAmount==null?"0.00":totalAmount);
        resultMap.put("realityAmount", realityAmount==null?"0.00":realityAmount);
        return resultMap;

    }

    @GetMapping("/queryStore")
    public List<Map<String, Object>> queryStore(@RequestParam Map<String, Object> params) {
        String providerId = FilterContextHandler.getName();
        params.put("providerId", providerId);
        List<Map<String, Object>> mapList = orderManagementDAO.queryStore(params);
        logger.error("OrderManagementController-->queryStore storeList:::" + JsonUtils.objectToJson(mapList));
        List<Map<String, String>> counterList = orderManagementDAO.queryCounter(params);
        logger.error("OrderManagementController-->queryStore counterList:::" + JsonUtils.objectToJson(counterList));
        for (Map<String, Object> store : mapList) {
            String storeId = (String) store.get("storeId");
            for (Map<String, String> counter : counterList) {
                String counterStoreId = counter.get("storeId");
                List storeCounterList = (List) store.get("counterList");
                if (null == storeCounterList) {
                    storeCounterList = new ArrayList();
                }
                if (storeId.equals(counterStoreId)) {
                    storeCounterList.add(counter);
                }
                store.put("counterList", storeCounterList);
            }
        }
        logger.error("OrderManagementController-->queryStore result:::" + mapList);
        return mapList;

    }


}
